﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FairyGUI;
using UnityEngine;

namespace Model
{
    [ObjectSystem]
    public class UIViewSystem : System
    {

        public override void Create()
        {
            GameRoot.Scene.AddComponent<UIViewComponent>();
        }

        /// <summary>
        /// await异步WWW方式加载AB包
        /// </summary>
        public async Task LoadViews()
        {
            UIViewComponent Uvc = GameRoot.Scene.GetComponent<UIViewComponent>();

            foreach (string name in Uvc.ViewNames)
            {
                if (Uvc.loadedPackage.Contains(name))
                    return;
                AssetBundle _cfg = await FileIOHelper.GetAssetBundle(Uvc.packagePath + name.ToLower() + "_cfg.ab");
                AssetBundle _res = await FileIOHelper.GetAssetBundle(Uvc.packagePath + name.ToLower() + "_res.ab");
                Uvc.loadedPackage.Add(name);
                Log.Info($"{name}加载完成");
                if (_res != null)
                {
                    UIPackage.AddPackage(_cfg, _res);
                }
                else
                {
                    UIPackage.AddPackage(_cfg);
                }
                
            }
            AddView(Uvc);
        }

        private void AddView(UIViewComponent u)
        {
            AssembliesComponent Asv = GameRoot.Scene.GetComponent<AssembliesComponent>();
            if (Asv.AllAttributes.ContainsKey(typeof(UIViewAttribute)))
            {
                foreach (Type type in Asv.AllAttributes[typeof(UIViewAttribute)])
                {
                    object[] attrs = type.GetCustomAttributes(typeof(UIViewAttribute), false);
                    if (attrs.Length == 0)
                    {
                        return;
                    }
                    UIViewAttribute uiViewAttribute = (UIViewAttribute)attrs[0];
                    if (!u.uiViewDict.ContainsKey(uiViewAttribute.Type))
                    {
                        object obj = Activator.CreateInstance(type);
                        u.uiViewDict.Add(uiViewAttribute.Type, (UIView)obj);
                    }
                    else
                    {
                        Log.Error($"{uiViewAttribute.Type}的UI页面出现了超过一次");
                    }
                }
            }
        }

        public void LoadScene(UIViewType type)
        {
            UIViewComponent Uvc = GameRoot.Scene.GetComponent<UIViewComponent>();

            Uvc.ShowScene?.Leave();
            Uvc.uiViewDict[type].Enter();
            Uvc.uiViewDict[type].OnEnter();
            Uvc.ShowScene = Uvc.uiViewDict[type];
        }
        public override void Destory()
        {
            GameRoot.Scene.RemoveComponent<UIViewComponent>();
        }
    }
}
